package com.solcoo.common.image.activity;

import java.io.File;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.RectF;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.solcoo.common.image.BitmapHelper;
import com.solcoo.common.security.EncryptUtil;
import com.solcoo.common.util.DensityUtil;
import com.solcoo.common.util.FileUtil;
import com.solcoo.common.util.StringUtil;
import com.solcoo.common.view.HCropView;
import com.solcoo.merchant.R;
import com.solcoo.merchant.util.DialogUtil;
import com.solcoo.merchant.util.ViewUtil;

public class CropActivity extends Activity {
	protected static final String TAG = "CropActivity";
	private Bitmap bitmap;
	private ImageView image;
	private Point screenSize;
	private float minScaleR;

	protected ProgressDialog progressDialog;
	private OnClickListener rotateListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// bitmap 还原
			matrix.reset();
			image.setImageMatrix(matrix);
			// 旋转bitmap
			Matrix newMatrix = new Matrix();
			if (v.getId() == R.id.left_rotate) {
				newMatrix.postRotate(-90);
			} else {
				newMatrix.postRotate(90);
			}
			Bitmap temp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
					bitmap.getHeight(), newMatrix, true);
			// 清空设置
			image.setImageBitmap(null);
			bitmap.recycle();
			bitmap = temp;
			reloadCropView(false);
		}

	};

	private void reloadCropView(boolean isFirst) {
		image.setImageBitmap(bitmap);
		minZoom();
		center(true, true);
		image.setImageMatrix(matrix);

		// 旋转
		RectF rect = new RectF();
		matrix.mapRect(rect);
		rect.right = (float) (rect.left + bitmap.getWidth()
				* Math.min(1.0, minScaleR));
		rect.bottom = (float) (rect.top + bitmap.getHeight()
				* Math.min(1.0, minScaleR));
		// 对输出的长宽进行处理
		float outputW, outputH;
		outputW = (float) (outputX * Math.min(1.0, minScaleR));
		outputH = (float) (outputY * Math.min(1.0, minScaleR));
		// 进一步进行过滤
		outputW = outputW < rect.right - rect.left ? outputW : rect.right
				- rect.left;
		outputH = outputH < rect.bottom - rect.top ? outputH : rect.bottom
				- rect.top;
		float initFrameSize = (rect.right - rect.left) < (rect.bottom - rect.top) ? (rect.right - rect.left)
				: (rect.bottom - rect.top);
		initFrameSize = initFrameSize * initFrameSizeScale;
		float min = outputW < outputH ? outputW : outputH;
		initFrameSize = initFrameSize > min ? initFrameSize : min;// 初始的裁剪框一定要大于
																	// 最小要求的裁剪框
		if (isFirst) {
			findViewById(R.id.save).setOnClickListener(save2cancelListener);
			findViewById(R.id.cancel).setOnClickListener(save2cancelListener);
			findViewById(R.id.left_rotate).setOnClickListener(rotateListener);
			findViewById(R.id.right_rotate).setOnClickListener(rotateListener);
			cropView = new HCropView(CropActivity.this, rect, initFrameSize,
					initFrameSize, outputH, outputW);
			addContentView(cropView, image.getLayoutParams());
		} else {
			cropView.init(rect, initFrameSize, initFrameSize, outputH, outputW);
			cropView.invalidate();
		}

	}

	private Matrix matrix;
	private HCropView cropView;

	private OnClickListener save2cancelListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			if (processBar.getVisibility() == View.VISIBLE)
				return;
			switch (v.getId()) {
			case R.id.save:
				v.setClickable(false);
				progressDialog.show();
				RectF rectF = cropView.getRectF();
				RectF rectFBitmap = cropView.getBitmapRectF();
				float scale = 1;
				if (minScaleR < 1)
					scale = minScaleR;
				int x = (int) ((rectF.left - rectFBitmap.left) / scale);
				int y = (int) ((rectF.top - rectFBitmap.top) / scale);
				int width = (int) ((rectF.right - rectF.left) / scale);
				int height = (int) ((rectF.bottom - rectF.top) / scale);
				// 保存数据 对图片进行压缩
				Matrix cropMatrix = new Matrix();
				float cropScale = Math.min(outputX / (float) width, outputY
						/ (float) height);
				if (cropScale < 1.0f)
					cropMatrix.postScale(cropScale, cropScale);
				Bitmap cropBitmap = Bitmap.createBitmap(bitmap, x, y, width,
						height, cropMatrix, true);
				// 设置输出路径
				outputUrl = getIntent().getStringExtra(OUTPUT_URL);
				File file;
				if (StringUtil.isEmpty(outputUrl)) {
					String md5FileName = EncryptUtil.md5Hex(cropImageUrl);
					file = new File(FileUtil.getImageCacheDir(), md5FileName);
				} else {
					file = new File(outputUrl);
				}
				if (BitmapHelper.storeImage(cropBitmap, file, 90)) {
					Intent data = new Intent();
					image.setImageBitmap(null);
					bitmap.recycle();
					cropBitmap.recycle();// 回收
					Log.d(TAG, "cropBitmap file.size(kb)=" + file.length()
							/ 1024);
					data.putExtra(OUTPUT_URL, file.getAbsolutePath());
					setResult(RESULT_OK, data);
					finish();
				}
				v.setClickable(true);
				DialogUtil.dimissDialog(progressDialog);
				break;
			case R.id.cancel:
				recycle();
				finish();// 关闭当前
				break;
			default:
				break;
			}

		}

	};
	private float outputX;
	private float outputY;
	private String cropImageUrl;
	private String outputUrl;
	private float initFrameSizeScale = 1.0f;
	public static final String OUTPUT_X = "outputX";// 输出尺寸 宽
	public static final String OUTPUT_Y = "outputY";// 输出尺寸 高
	public static final String OUTPUT_URL = "outputUrl";// 输出图片的地址
	public static final String CROP_IMAGE_URL = "cropImageUrl";// 待切割的图片地址
	public static String FRAME_SIZE_SCALE = "frame_size_scale";// 初始相框的大小为
																// 屏幕宽的几分之几
																// float
	private View processBar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.crop_image);

		progressDialog = ViewUtil.createProgressDialog(this, "正在保存图片");
		processBar = findViewById(R.id.progress);
		TextView tvProgressText = (TextView) processBar
				.findViewById(R.id.process_msg_txt);
		tvProgressText.setText("图片加载中");
		Intent intent = getIntent();
		cropImageUrl = intent.getStringExtra(CROP_IMAGE_URL);
		if (StringUtil.isEmpty(cropImageUrl)) {// 如果是空值的话
			finish();
			return;
		}
		// 异步加载bitmap
		processBar.setVisibility(View.VISIBLE);
		LoadImageTask loadImageTask = new LoadImageTask();
		loadImageTask.execute(cropImageUrl);

	}

	/** * 横向、纵向居中 */
	protected void center(boolean horizontal, boolean vertical) {
		Matrix m = new Matrix();
		m.set(matrix);
		RectF rect = new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight());
		m.mapRect(rect);
		float height = rect.height();
		float width = rect.width();
		float deltaX = 0, deltaY = 0;
		if (vertical) {
			// 图片小于屏幕大小，则居中显示。大于屏幕，上方留空则往上移，下放留空则往下移
			int screenHeight = screenSize.y;
			if (height < screenHeight) {
				deltaY = (screenHeight - height) / 2 - rect.top;
			} else if (rect.top > 0) {
				deltaY = -rect.top;
			} else if (rect.bottom < screenHeight) {
				deltaY = image.getHeight() - rect.bottom;
			}
		}
		if (horizontal) {
			int screenWidth = screenSize.x;
			if (width < screenWidth) {
				deltaX = (screenWidth - width) / 2 - rect.left;
			} else if (rect.left > 0) {
				deltaX = -rect.left;
			} else if (rect.right < screenWidth) {
				deltaX = screenWidth - rect.right;
			}
		}
		matrix.postTranslate(deltaX, deltaY);
	}

	/** * 最小缩放比例，最大为100% */
	private void minZoom() {
		minScaleR = Math.min((float) screenSize.x / (float) bitmap.getWidth(),
				(float) screenSize.y / (float) bitmap.getHeight());
		if (minScaleR < 1.0) {
			Log.i(">>_minScaleR", "minScaleR=" + minScaleR);
			matrix.postScale(minScaleR, minScaleR);
		}
		Log.i(">>_minScaleR_wh",
				"wh=" + bitmap.getWidth() + "," + bitmap.getHeight());
	}

	class LoadImageTask extends AsyncTask<String, Void, Bitmap> {

		@Override
		protected Bitmap doInBackground(String... params) {
			Bitmap bitmap = BitmapHelper.readBitmapAutoSize(
					new File(params[0]), BitmapHelper.MAX_PHOTO_SIZE_640,
					BitmapHelper.MAX_PHOTO_SIZE_640);
			return bitmap;

		}

		@Override
		protected void onPostExecute(Bitmap result) {
			super.onPostExecute(result);
			bitmap = result;// 赋值
			if (bitmap == null) {
				finish();
				return;
			}
			// 取出尺寸
			Intent intent = getIntent();
			outputX = intent.getIntExtra(OUTPUT_X, 640);
			outputY = intent.getIntExtra(OUTPUT_Y, 640);
			initFrameSizeScale = intent.getFloatExtra(FRAME_SIZE_SCALE, 1.0f);
			// 拿到屏幕的大小
			DisplayMetrics metrics = getResources().getDisplayMetrics();
			screenSize = new Point();
			screenSize.y = metrics.heightPixels - DensityUtil.dip2px(45f);
			screenSize.x = metrics.widthPixels;
			// 取出待裁剪的图片
			image = (ImageView) findViewById(R.id.image);
			// 初始化
			matrix = new Matrix();
			reloadCropView(true);
			processBar.setVisibility(View.GONE);

		}

	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		recycle();
	}

	private void recycle() {
		if (bitmap != null && !bitmap.isRecycled()) {
			image.setImageBitmap(null);
			bitmap.recycle();
		}
	}
}
